<template>
  <div>
    <el-dialog :visible="dialogFormVisible" :show-close="false">
      <el-form
        ref="form"
        :model="form"
        :label-width="formLabelWidth"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="$emit('update:dialogFormVisible', false)"
        >取 消</el-button>
        <el-button type="primary" @click="showRole">确 定</el-button>
      </div>
      <div slot="title" class="dialog-title">
        <p>{{ isEdit ? '编辑角色' : '添加角色' }}</p>
        <span
          class="el-icon-close"
          @click="$emit('update:dialogFormVisible', false)"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addRolesApi, editRolesApi } from '@/api/settings'
export default {
  name: '',
  props: {
    dialogFormVisible: {
      type: Boolean
    },
    isEdit: {
      type: Boolean
    },
    row: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      form: {
        name: '',
        description: ''
      },
      formLabelWidth: '120px',
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {
    row(newVal) {
      this.form = { ...newVal, permIds: [] }
    }
  },
  created() {},
  methods: {
    showRole() {
      this.$refs.form.validate(async(valid) => {
        if (!valid) return this.$message.error('请输入内容')
        this.isEdit ? this.doEdit() : this.doAdd()
      })
      this.$emit('update:dialogFormVisible', false)
    },
    async doAdd() {
      await addRolesApi(this.form)
      this.$emit('success') // 立即刷新
      this.form = {
        name: '',
        description: ''
      }
      this.$refs.form.resetFields()
    },
    async doEdit() {
      await editRolesApi(this.form)
      this.$emit('success') // 立即刷新
      this.form = {
        name: '',
        description: ''
      }
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style lang="scss" scoped>
.dialog-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
